#define _CRT_SECURE_NO_WARNINGS  1

#include"List.h"

bool ListEmpty(ListNode* pHead)
{
	assert(pHead);
	return pHead->next = pHead;
}

ListNode* LTInit()
{
	ListNode* pHead = BuyListNode(-1);
	pHead->next = pHead;
	pHead->prev = pHead;

	return pHead;
}

void ListDestory(ListNode* pHead)
{
	assert(pHead);

	ListNode* cur = pHead->next;
	while (cur!=pHead)
	{
		ListNode* next = cur->next;
		free(cur);
		cur = next;
	}
	free(pHead);
}

ListNode* BuyListNode(LTDataType x)
{
	ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	if (newnode == NULL)
	{
		perror("malloc fail");
		return;
	}
	newnode->data = x;
	newnode->next = NULL;
	newnode->prev = NULL;
}

void ListPushBack(ListNode* pHead, LTDataType x)
{
	ListNode* newnode = BuyListNode(x);
	ListNode* tail = pHead->prev;

	//pHead     tail  newnode
	tail->next = newnode;
	pHead->prev = newnode;
	newnode->prev = tail;
	newnode->next = pHead;
}

void ListPushFront(ListNode* pHead, LTDataType x)
{
	ListInsert(pHead->next,x);
}

void ListPopBack(ListNode* pHead)
{
	ListErase(pHead->prev);
}

void ListPopFront(ListNode* pHead)
{
	ListErase(pHead->next);
}

void ListPrint(ListNode* pHead)
{
	assert(pHead);
	ListNode* cur = pHead->next;
	printf("<=Head=>");
	while (cur!=pHead)
	{
		printf("<=%d=>", cur->data);
		cur = cur->next;
	}
	printf("\n");
}

void ListInsert(ListNode* pos, LTDataType x)
{
	assert(pos);
	ListNode* newnode = BuyListNode(x);
	ListNode* prev = pos->prev;

	prev->next = newnode;
	newnode->prev = prev;

	newnode->next = pos;
	pos->prev = newnode;
}

void ListErase(ListNode* pos)
{
	assert(pos);
	ListNode* next = pos->next;
	ListNode* prev = pos->prev;

	prev->next = next;
	next->prev = prev;
	free(pos);
}

ListNode* ListFind(ListNode* pHead, LTDataType x)
{
	assert(pHead);

	ListNode* cur = pHead->next;
	while (cur!=pHead)
	{
		if (cur->data == x)
		{
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}